package com.xdap.keymen.service.dayang;

import com.definesys.mpaas.query.MpaasQuery;
import com.xdap.keymen.entity.dayang.DaYangCouponDistributionDetailsEntity;
import com.xdap.keymen.entity.dayang.DaYangOrderTitleEntity;
import com.xdap.keymen.entity.dayang.DaYangStoredValueRecordEntity;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class DaYangOrderTitleService {
    private final RuntimeDatasourceService runtimeDatasourceService;
    private final RuntimeAppContextService runtimeAppContextService;
    private final SnowflakeIdWorker snowflakeIdWorker;

    public DaYangOrderTitleEntity getOrderDetail(String id) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.eq("id", id);
        return query.doQueryFirst(DaYangOrderTitleEntity.class);
    }

    /**
     * Update coupon distribution callback.
     *
     * @param daYangOrderTitleEntity {@link DaYangStoredValueRecordEntity}
     * @return Ture or False.
     */
    public Integer updateCouponDistributionDetailsCallback(DaYangOrderTitleEntity daYangOrderTitleEntity) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.update("up_flag", daYangOrderTitleEntity.getUpFlag());
        query.update("up_error_msg", daYangOrderTitleEntity.getUpErrorMsg());
        query.eq("id", daYangOrderTitleEntity.getId());
        return query.doUpdate(daYangOrderTitleEntity);
    }

    /**
     * 创建随机数
     *
     * @return 随机数
     */
    public String createRandomNo() {
        int min = 1;
        int max = 999999;
        int randomNo = (int) (Math.random() * (max - min + 1) + min);
        return String.format("%06d", randomNo);
    }
}
